package com.tdh.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@Slf4j
public class FilesUtil {


    /**
     * 设置路径下自定义文件夹
     * @param path 自定义路径
     * @return 存储路径
     */
    public static String getTempFilePath(String path) {
        ServletContext servletContext = ContextLoader.getCurrentWebApplicationContext().getServletContext();
        return servletContext.getRealPath(path);
    }

    /**
     * 将临时文件夹里的文件复制到目标文件夹
     * @param srcPath 临时文件夹路径
     * @param destPath 目标文件夹路径
     * @return boolean 是否操作成功
     * @throws IOException 异常
     */
    public static boolean copy(String srcPath, String destPath) throws IOException {
        FileUtils.copyFileToDirectory(new File(srcPath), new File(destPath), true);
        return true;
    }

    /**
     * 将上传文件保存到临时文件夹
     * @param file 文件对象
     * @param path 临时文件路径 temp/yyyyMMdd/
     * @return 全局唯一文件名
     * @throws IOException 异常
     */
    public static String uploadImg(MultipartFile file, String path) throws IOException {

        String uploadFileName = UUID.randomUUID()+file.getOriginalFilename();

        //临时文件夹，如果路径不存在，创建一个
        File realPath = new File(path);
        if (!realPath.exists()) {
            realPath.mkdirs();
        }

        //将文件保存到临时文件夹
        file.transferTo(new File(path + uploadFileName));
        return uploadFileName;
    }

    /**
     * 删除指定路径文件
     * @param pathList 文件路径数组
     * @return boolean
     */
    public static boolean deleteFile(List<String> pathList) {
        int count = 0;

        for(String path: pathList) {
            File deleteFile = new File(path);
            if(deleteFile.exists() && deleteFile.isFile() && deleteFile.delete()) {
                count++;
                log.warn("删除文件：{}", path);
            }
        }
        return count == pathList.size();
    }
}
